import { message } from "antd";
import { useContext, useEffect, useRef, useState } from "react";
import { AppContext, isExternal } from "..";
export const fileToBlob = (file) => {

    const blob = new Blob([file], { type: file.type });
    const blobUrl = URL.createObjectURL(blob);
    return blobUrl
}
const isString = (value: any) => {
    return typeof value === 'string'
}
const isFunction = (value: any) => {
    return typeof value === 'function'
}
const isSuccess = (res) => {
    return res.code == 200
}
const showErrorMsg = (res: any) => {
    message.error(res.msg)
}
const useUpload = (props) => {
    const showFileName = useRef<any>([]);

    const { fileBasicUrl = '', upload = { action: '' }, apiPrefix, commonHeaders } = useContext(AppContext)
    const fileKey = upload.fileKey || "fileStorageName";
    let action = props.action || upload.action
    if (apiPrefix && !isExternal(action)) {
        action = `${apiPrefix}${action}`
    }
    const { dataType,onFileNameChange, fileName, onChange, maxCount, children, ...rest } = props
    const [uploadFiles, setUploadFiles] = useState([])
    // const [limtMap, setLimtMap] = useState({});
    // const [uploadFiles,setUploadFiles] = useState([])
    const isControlled = rest.hasOwnProperty('value')
    useEffect(() => {
        let _fileName =
            typeof fileName === "string"
                ? (fileName || "").split(",").filter(Boolean)
                : fileName;
        showFileName.current = _fileName||[];
    }, [fileName]);

    useEffect(() => {
        const value: string = rest.value
        // console.log('ssssss', rest.value)
        if (value) {
            value.split(',').filter(Boolean).forEach((url, index) => {
                const item = uploadFiles.find(v => v.url == url);
                if (!item) {

                    uploadFiles.push({
                        name:showFileName.current[index] || url,
                        url,
                        percent:100,
                        status: 'done',
                        uid: Math.random(),
                        thumbUrl: isExternal(url)?url: fileBasicUrl + url
                    })
                }
            })
            setUploadFiles([...uploadFiles])
        }
    }, [rest.value])
   const noticeChange = ()=>{
    const files = uploadFiles.filter(v => v.status == 'done').map(item => {
        return item.url;
    })
    // if (limtMap[uid]) {
    //     delete limtMap[uid];
    //     setLimtMap({ ...limtMap });
    // }
    onFileNameChange && onFileNameChange(showFileName.current);

    onChange(dataType === "array" ? files : files.join(",") as any);
   }
    const _onChange = (info) => {
        console.log({ info })

        if (!isControlled) {
            if (onChange) {
                return onChange(info)
            }
        }
        
        const { status, name, uid, originFileObj } = info.file
        const index = uploadFiles.findIndex(v => v.uid === uid)
        if (index == -1) {
            // if (uploadFiles.length >= maxCount) {
            //     console.log('uploadFiles[0].status',uploadFiles[0].status)
            //     if(uploadFiles[0].status!='uploading'){
            //         limtMap[uid] = uploadFiles[0];
            //         setLimtMap({ ...limtMap });
            //     }


            //     uploadFiles.splice(0, 1);
            //     showFileName.current.splice(0, 1)


            // }
            showFileName.current.push(name);

            uploadFiles.push({
                status,
                name,
                percent:0,
                thumbUrl: fileToBlob(originFileObj),
                uid,
            })
            // uploadFiles[uid] = {
            //     status,
            //     uid
            // }
        }else{
            console.log('info.file.percent',info.file.percent)
            uploadFiles[index].percent = info.file.percent;
        }
        if (isControlled) {
            setUploadFiles([...uploadFiles])
        }
        if (status === 'done') {
            uploadFiles[index].status = 'done'
            const response = info.file.response
            if (isSuccess(response)) {
                if(isString(response.data)){
                    uploadFiles[index].url =  response.data

                }else{
                    uploadFiles[index].url =  response.data[fileKey]
                    
                }
                if (uploadFiles.filter(v => v.status == 'done').length > maxCount) {

                    uploadFiles.splice(0, 1);
                    setUploadFiles([...uploadFiles]);
                }
                noticeChange()
                // const files = uploadFiles.filter(v => v.status == 'done').map(item => {
                //     return item.url;
                // })
               
                // onFileNameChange && onFileNameChange(showFileName.current);

                // onChange(dataType === "array" ? files : files.join(",") as any);

            } else {

                showErrorMsg(response)
                uploadFiles.splice(index, 1)
                showFileName.current.splice(index, 1)
                // if (limtMap[uid]) {
                //     uploadFiles.unshift(limtMap[uid]);
                //     showFileName.current.unshift(limtMap[uid].name);

                // }
                setUploadFiles([...uploadFiles])
            }


            // onChange()
        }
        if (status === 'error') {

            uploadFiles.splice(index, 1)
            showFileName.current.splice(0, 1)

            // if (limtMap[uid]) {
            //     uploadFiles.unshift(limtMap[uid])

            // }
            setUploadFiles([...uploadFiles]);
        }

    }
    const onRemove = (file) => {

        let findIndex = uploadFiles.findIndex((item: { uid: any; }) => item.uid === file.uid);
        if (findIndex > -1) {
            uploadFiles.splice(findIndex, 1);
            console.log(showFileName, "showFileName");
            if (Array.isArray(showFileName.current)) {
                showFileName.current.splice(findIndex, 1);
            }
        }
        noticeChange()
        // noticeChange(fileList);
    }
    const onPreview = (file)=>{
        let url = file.url
        if(!isExternal(url)){
            url = fileBasicUrl+url
        }
        window.open(url)
    }
    return {
        ...props,
        action,
        maxCount,
        onRemove,
        onPreview,
        headers: commonHeaders,
        onChange: _onChange,
        fileList: isControlled ? uploadFiles : undefined,
        children:uploadFiles.length>=maxCount?null:children,
        multiple: true
    }
}
export default useUpload